package com.swipemaster.activities;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;

import com.google.ads.AdView;
import com.google.analytics.tracking.android.EasyTracker;
import com.purplebrain.adbuddiz.sdk.AdBuddiz;
import com.purplebrain.adbuddiz.sdk.AdBuddizDelegate;
import com.swipemaster.R;
import com.swipemaster.common.AdMobFullscreen;
import com.swipemaster.common.AdMobListener;
import com.swipemaster.common.Const;
import com.swipemaster.common.Global;
import com.swipemaster.game.modes.ChallengeMode;
import com.swipemaster.game.modes.CustomMode;
import com.swipemaster.game.modes.GameMode;
import com.swipemaster.network.Network;
import com.swipemaster.network.Security;

/** Starting point of application. */
public class MainActivity extends CommonActivity implements AdBuddizDelegate
{
	private TextView titleText;
	private Button playLevels;
	private Button playChallenge;
	private Button playCustom;
	private Button highScores;
	private Button music;
	private Button exit;
	private final Handler handler = new Handler();
	private final int ANIM_TIME = 1000;
	private boolean backAlreadyPressed = false;

	public static final Map<String, AdMobFullscreen> fullscreens = new HashMap<String, AdMobFullscreen>();

	@Override
	public void failToLoadAd(String placementId, AdBuddizFailToDisplayCause cause)
	{
		if (!Network.isConnected() || !fullscreens.containsKey(placementId)
				|| !fullscreens.get(placementId).adView.isReady())
		{
			return;
		}

		final Intent intent = new Intent(this, FullscreenActivity.class);
		intent.putExtra(FullscreenActivity.EXTRAS_KEY, placementId);
		startActivity(intent);
	}

	@Override
	public void onBackPressed()
	{
		if (backAlreadyPressed)
		{
			return;
		}
		backAlreadyPressed = true;

		Global.app.musicPlayer.stopMusic();
		setAnimations(true);
		setViewsVisibility(View.INVISIBLE);
		titleText.setVisibility(View.VISIBLE);
		handler.postDelayed(new Runnable()
		{
			@Override
			public void run()
			{
				MainActivity.super.onBackPressed();
			}
		}, ANIM_TIME);

		AdBuddiz.getInstance().showAd(AdMobListener.AD_1);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		setContentView(R.layout.main);
		EasyTracker.getInstance().activityStart(this);

		AdMobFullscreen fullscreen = new AdMobFullscreen(this);
		Global.app.adMobListener.hashToNameMap.put(fullscreen.adView.hashCode(), AdMobListener.AD_1);
		fullscreens.put(AdMobListener.AD_1, fullscreen);

		fullscreen = new AdMobFullscreen(this);
		Global.app.adMobListener.hashToNameMap.put(fullscreen.adView.hashCode(), AdMobListener.AD_2);
		fullscreens.put(AdMobListener.AD_2, fullscreen);

		AdBuddiz.getInstance().setDelegate(this);
		AdBuddiz.getInstance().cacheAds(this);

		final AdView banner = (AdView) findViewById(R.id.main_banner);
		banner.setAdListener(Global.app.adMobListener);
		Global.app.adMobListener.hashToNameMap.put(banner.hashCode(), AdMobListener.AD_3);

		setButtons();
		Global.app.musicPlayer.continueMusic = false;
		Security.setUserId(this);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onStart()
	{
		AdBuddiz.getInstance().onStart(this);
		setAnimations(false);
		super.onStart();
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	private View.OnClickListener getListener(final Class<? extends Activity> activityCls,
			final Class<? extends GameMode> gameModeCls, final Button button, final boolean continueMusic)
	{
		return new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setAnimations(true);
				setDisappearAnimationForView(titleText, 0, ANIM_TIME);
				setViewsVisibility(View.INVISIBLE);

				handler.postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						Global.app.musicPlayer.continueMusic = continueMusic;

						try
						{
							if (gameModeCls != null)
							{
								Global.app.gameMode = gameModeCls.newInstance();
							}
						}
						catch (final Exception e)
						{
							e.printStackTrace();
						}

						startActivity(new Intent(MainActivity.this, activityCls));

						if (button.equals(highScores))
						{
							overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
						}
						else
						{
							overridePendingTransition(0, 0);
						}
					}
				}, ANIM_TIME);

				handler.postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						setViewsVisibility(View.VISIBLE);
					}
				}, 1600);
			}
		};
	}

	private void setAnimationForView(Button view, int which, long animTime)
	{
		final int NUMBER_OF_BUTTONS = 7;
		final float fromYValue = ((float) (which + 1) / NUMBER_OF_BUTTONS) * Global.app.consts.height;

		final TranslateAnimation animation = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0,
				Animation.ABSOLUTE, -fromYValue, Animation.ABSOLUTE, 0);
		animation.setInterpolator(new BounceInterpolator());
		animation.setDuration(animTime);
		view.setAnimation(animation);
	}

	private void setAnimations(boolean isDisappear)
	{
		final Button[] buttons =
		{ playLevels, playChallenge, playCustom, highScores, music, exit };
		for (int i = 0; i < buttons.length; i++)
		{
			if (isDisappear)
			{
				setDisappearAnimationForView(buttons[i], i, ANIM_TIME);
			}
			else
			{
				setAnimationForView(buttons[i], i, ANIM_TIME);
			}
		}
	}

	private void setButtons()
	{
		titleText = (TextView) findViewById(R.id.title);
		playLevels = (Button) findViewById(R.id.play_levels);
		playChallenge = (Button) findViewById(R.id.play_challenge);
		playCustom = (Button) findViewById(R.id.play_custom);
		highScores = (Button) findViewById(R.id.high_scores);
		music = (Button) findViewById(R.id.music_button);
		exit = (Button) findViewById(R.id.exit);
		setFont();
		setListeners();
	}

	private void setDisappearAnimationForView(View view, int which, long animTime)
	{
		final Interpolator interpolator = new AnticipateInterpolator(0.1f + (0.38f * which));

		final int NUMBER_OF_BUTTONS = 7;
		final float toYValue = (2f * Global.app.consts.height)
				- ((float) ((which - 1) / NUMBER_OF_BUTTONS) * Global.app.consts.height);
		final TranslateAnimation animation = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0,
				Animation.ABSOLUTE, 0, Animation.ABSOLUTE, toYValue);
		animation.setInterpolator(interpolator);
		animation.setDuration(animTime);
		view.setAnimation(animation);
	}

	private void setFont()
	{
		titleText.setTypeface(Global.app.consts.font);
		final int shadowRadious = Global.app.consts.dpToPx(Const.titleShadowRadiousDp);
		final int shadowDx = Global.app.consts.dpToPx(Const.titleShadowDxDp);
		titleText.setShadowLayer(shadowRadious, shadowDx, shadowDx, Color.parseColor(Const.titleTextShadowColorString));
		final Button[] buttons =
		{ playLevels, playChallenge, playCustom, highScores, music, exit };
		for (final Button button : buttons)
		{
			button.setTypeface(Global.app.consts.font);
		}
	}

	private void setListeners()
	{
		playLevels.setOnClickListener(getListener(PlayLevelsActivity.class, null, playLevels, true));
		playChallenge.setOnClickListener(getListener(GameActivity.class, ChallengeMode.class, playChallenge, false));
		playCustom.setOnClickListener(getListener(CustomGameActivity.class, CustomMode.class, playCustom, true));
		highScores.setOnClickListener(getListener(HighScoresActivity.class, null, highScores, true));
		setMusicText();
		music.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				final boolean enabled = Global.app.musicPlayer.isEnabled();
				Global.app.musicPlayer.setEnabled(!enabled);
				setMusicText();
			}
		});

		exit.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				handler.postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						onBackPressed();
					}
				}, Const.BUTTON_CLICK_ANIM_DURATION);
			}
		});
	}

	private void setMusicText()
	{
		if (Global.app.musicPlayer.isEnabled())
		{
			music.setText(R.string.music_on);
		}
		else
		{
			music.setText(R.string.music_off);
		}
	}

	private void setViewsVisibility(int visibility)
	{
		final Button[] buttons =
		{ playLevels, playChallenge, playCustom, highScores, music, exit };
		titleText.setVisibility(visibility);
		for (final Button button : buttons)
		{
			button.setVisibility(visibility);
			if (visibility == View.INVISIBLE)
			{
				button.setEnabled(false);
			}
			else
			{
				button.setEnabled(true);
			}
		}
	}
}